<template>
  <div class="container" :style="pageStyle">
    <!-- 这是操作提示 -->
    <div class="guideMask" @click="hideGuideMask" v-if="showGuide">
      <div
        class="guideMaskImg"
        :style="'background:url('+guideImg+') center center / contain no-repeat;'"
      ></div>
    </div>
    <!-- <div class="mask" @click="doClick"></div> -->
    <!-- 这是加载中遮罩，防止用户看到页面跳动 -->
    <!-- <transition name="fade">
      <div v-show="showLoadingMask" class="loading_mask"></div>
    </transition>-->
    <div id="area" @click="doClick"></div>
    <tool-bar
      :isShow="showToolBar"
      :progress="progress"
      :fontSize="fontSize"
      :selectedColor="themeName"
      @onChangeFontsize="onChangeFontsize"
      @onThemeSelect="onThemeSelect"
      @openCatalog="openCatalog"
      ref="toolBar"
    />
    <catagory :showCatagory="showCatagory" :toc="toc" @gotoPage="gotoPage"/>
    <cc-dialog
      :isShow="BuyDialog"
      @onCancel="cancelDialog"
      @onConfirm="goBuy"
      message="該內容需要購買才可繼續閱讀"
      confirmText="立即購買"
    />
  </div>
</template>

<script>
import ToolBar from "../components/ReaderToolBar";
import Catagory from "../components/catagory.vue";
import CcDialog from "../components/dialog.vue";

import axios from "axios";

import ePub from "../epub/epub.js";
import jszip from "../epub/jszip.min.js";

let OSS = require("ali-oss");
var CryptoJS = require("crypto-js");

import { defer, isXml, parse } from "../epub/utils/core";
import Path from "../epub/utils/path";
import { setTimeout } from "timers";

export default {
  data() {
    return {
      isNative: false,
      isLogin: false,
      bookSrc: null,
      bookId: null,
      bookData: null,
      progress: 0,
      book: null,
      rendition: null,
      showCatagory: 0,
      toc: null,
      clientWidth: 0,
      loading: false,
      showToolBar: null,
      show: null,
      windowWidth: 500,
      windowHeight: 500,
      testTime: 0,
      toolbarIsShow: false,
      BuyDialog: false,
      fontSize: 1,
      themeName: 0,
      backgroundColor: null,
      needBuy: false,
      ossConfig: null, // 阿里云秘钥对象
      showGuide: false,
      limitSection: null,
      guideImg: require("@/assets/image/icon/guide.png"),
      checkPage: true, //是否需要校正
      showLoadingMask: true,
      historyPage: 1,
      tryTime: 1,
      localPathname: null
    };
  },
  watch: {},
  computed: {
    pageStyle() {
      if (this.backgroundColor) {
        return {
          "background-color": this.backgroundColor
        };
      } else {
        return {
          "background-color": this.$config.themes[this.themeName].color
        };
      }
    }
  },

  components: {
    ToolBar,
    Catagory,
    CcDialog,
    OSS
  },
  mounted() {
    window["dataTransmission"] = this.dataTransmission;
    try {
      native.webViewOnload();
      this.isNative = true;
      native.hideNavigation();
      native.interactivePopDisabled(true); // 禁止ios左滑返回操作
      native.disabledBounce(); //禁止上下滾動
    } catch (error) {}

    let localPath = window.location.origin + window.location.pathname;
    let paths = localPath.split("/");
    let newPath = "";
    paths.forEach((str, index) => {
      if (index < paths.length - 1) {
        newPath += str + "/";
      }
    });
    this.localPathname = newPath;

    this.windowWidth = document.body.clientWidth;
    this.windowHeight = document.body.clientHeight * 0.97; //document.body.clientHeight; 預留topbar位置
    this.clientWidth = document.body.clientWidth;
    this.bookId =
      this.$route.query.src ||
      // decodeURIComponent(
      //   "http%3A%2F%2Fnowbook-info.oss-cn-hongkong.aliyuncs.com%2FLzE1NDYyMzUzNTgwOTMwMDNfMW0uZXB1Yg%3FExpires%3D1546238956%26OSSAccessKeyId%3DLTAI3MlVyHfQ7xyf%26Signature%3DyWguN9IDBTZMH%252FvZNk09GWIIKJ0%253D"
      // );
      //"b130c9002b0147ecbdce720a7d431c57"; //250M
      //"b15dd45d8dd746bc82e71425ba33c172";
      //"bf1d5e9f325c44a5a882679b953ca694";
      "05b4cbe0473d407fbfe4d6d962316d23";

    //讀取客戶端緩存，判斷是否首次，顯示指引
    if (this.isNative) {
      var dataValue = native.getStorage("reader_showGuide");
      try {
        let settingObj = JSON.parse(dataValue);
        this.showGuide = false;
      } catch (error) {
        this.showGuide = true;
      }
    }

    //判断用户是否登录
    this.LOGIN.get(false).then(res => {
      if (res.session != null) {
        this.isLogin = true;
      } else {
        this.isLogin = false;
      }
    });

    //this.getEbookInfo(); //调试

    if (!this.isNative) {
      this.getEbookInfo();
    }
  },
  methods: {
    hideGuideMask() {
      this.showGuide = false;
      let settingObj = {
        showGuide: 1
      };
      //保存設置到本地
      if (this.isNative) {
        var setData = {
          key: "reader_showGuide",
          value: JSON.stringify(settingObj)
        };
        native.setStorage(JSON.stringify(setData));
      }
    },
    dataTransmission(params) {
      try {
        let obj = JSON.parse(params);
        this.bookId = obj.id; //ID
        this.historyCfi = obj.cfi || null; //進度
        this.limitSection = obj.limitSection || 2; //顯示張姐
        if (this.book) {
          this.book.destroy(); // 銷毀當前書籍，重新渲染
          this.rendition.clear();
          document.getElementById("area").innerHTML = ""; //清空HTML内容
        }
        if (this.bookId) {
          this.getEbookInfo();
        }
      } catch (error) {}
    },

    goBuy() {
      this.BuyDialog = false;
      let obj = {
        router: this.$router,
        path: "index.html#/app/buy",
        query: {
          objType: "media",
          id: this.bookId
        }
      };
      //监听窗口关闭窗口返回事件
      window["prevWindowsParams"] = this.buyCallback;
      window["closeWindowsCallback"] = this.buyCallback;
      this.GLOBAL_.ccApp.openTo(obj);
    },

    //購買回調
    buyCallback() {
      this.getEbookInfo();
      if (this.book) {
        this.book.destroy(); // 銷毀當前書籍，重新渲染
        this.rendition.clear();
        document.getElementById("area").innerHTML = ""; //清空HTML内容
      }
    },

    cancelDialog() {
      this.BuyDialog = false;
    },

    getEbookInfo() {
      if (this.isNative) {
        native.showLoadingText("加載中...");
      }

      this.needBuy = false;
      let postD = {
        id: this.bookId
      };
      this.GLOBAL_.ccRequest
        .doSessionAxios(this.CONFIG.MEDIA.GET, postD, "GET", "no login")
        .then(res => {
          this.bookData = res;
          this.bookSrc = res.mediaValue;

          if (res.ebookProgress) {
            //歷史記錄
            this.historyCfi = res.ebookProgress.cfi;
            this.historyPage = res.ebookProgress.page || 1;
            console.log("历史记录页数：", this.historyPage);

            // this.historyCfi = {
            //   start: {
            //     index: 9,
            //     href: "chapter3.xhtml",
            //     cfi: "epubcfi(/6/20[isbn9789888488315_3]!/4/22/4/2/1:0)",
            //     displayed: { page: 5, total: 59 },
            //     location: -1,
            //     percentage: 0
            //   },
            //   end: {
            //     index: 9,
            //     href: "chapter3.xhtml",
            //     cfi: "epubcfi(/6/20[isbn9789888488315_3]!/4/14/1:93)",
            //     displayed: { page: 5, total: 59 },
            //     location: -1,
            //     percentage: 0
            //   }
            // };
            //試讀限制
          }
          //未购买、可试阅
          if (res.isBuy != 1 && res.salePrice > 0 && res.canTry > 0) {
            this.limitSection = res.probation;
          } else {
            this.limitSection = null;
          }

          this.ossConfig = {
            region: "oss-cn-hongkong",
            accessKeyId: res.token.accessKeyId,
            accessKeySecret: res.token.accessKeySecret,
            stsToken: res.token.securityToken,
            bucket: "nowbook-info"
          };

          this.loadBook(this.bookId);

          //this.getPlayUrl(); //獲取播放地址
          // this.getToken(this.bookId)
          //   .then(_ => {
          //     this.loadBook(this.bookId);
          //   })
          //   .catch(err => {
          //     native.showToast("加载数据失败");
          //     native.hideLoading();
          //   });
        })
        .catch(err => {
          //獲取多媒體數據異常
          if (this.isNative) {
            native.showToast("加载数据失败");
            native.hideLoading();
          }
        });
    },

    //获取阿里云token
    getToken(id) {
      let that = this;
      return new Promise(function(resolve, reject) {
        let url = that.CONFIG.epub.getToken;
        let postD = {
          id: id
        };

        that.GLOBAL_.ccRequest
          .doSessionAxios(url, postD, "GET", "no login")
          .then(res => {
            that.ossConfig = {
              region: "oss-cn-hongkong",
              accessKeyId: res.accessKeyId,
              accessKeySecret: res.accessKeySecret,
              stsToken: res.securityToken,
              bucket: "nowbook-info"
            };

            resolve();
          })
          .catch(err => {
            reject();
          });
      });
    },

    //对URL进行加密
    signatureUrl(path, opt) {
      // let client = new OSS(this.ossConfig);
      // return client.signatureUrl(path, opt) + "&" + new Date().getTime(); //加上随机数，避免缓存
      console.log("path=>", path);

      // let url =
      //   "https://devapi.nowbook.sup.services/api/media/epub/read/" +
      //   this.bookId +
      //   path;

      let url = this.SERVER.URL + "api/media/epub/read/" + this.bookId + path;
      console.log("url===>", url);
      return url;
    },

    //获取图片URL
    getImageUrl(imgPath) {
      // let imgUrl = `https://devapi.nowbook.sup.services/api/media/epub/read/${
      //   this.bookId
      // }${imgPath}?process=image/resize,w_${parseInt(
      //   this.windowWidth * this.DPR
      // )}`;
      let imgUrl = `${this.SERVER.URL}api/media/epub/read/${
        this.bookId
      }${imgPath}?process=image/resize,w_${parseInt(
        this.windowWidth * this.DPR
      )}`;
      return imgUrl;

      // return this.signatureUrl(this.bookId + imgPath, {
      //   process: "image/resize,w_" + parseInt(this.windowWidth * this.DPR) // 根据屏幕宽度选择合适的尺寸
      //   // process: "image/resize,w_" + this.windowWidth // 根据屏幕宽度选择合适的尺寸
      // });
    },

    loadData() {},

    getChapterNum(url) {
      let chapterNum = -1;
      //正则匹配
      let reg = /chapter(\d+)\.xhtml/gi;
      let result = null;
      if ((result = reg.exec(url)) != null) {
        chapterNum = result[1] * 1;
      }

      //匹配是否最后的postscript
      let reg2 = /postscript(\d+)\.xhtml/gi;
      let result2 = null;
      if ((result2 = reg2.exec(url)) != null) {
        chapterNum = 9999;
      }

      //匹配是否最后的postscript
      let reg3 = /bibliography(\d+)\.xhtml/gi;
      let result3 = null;
      if ((result3 = reg3.exec(url)) != null) {
        chapterNum = 9999;
      }

      return chapterNum;
    },

    checkChapterCanRead(url) {
      console.log("检查章节是否可阅读章节=>", url);
      // console.log("this.toc=>", JSON.stringify(this.toc));

      if (this.limitSection == null) {
        return true;
      }

      if (this.toc != null) {
        let ct = false;
        for (let index = 0; index < this.toc.length; index++) {
          if (url.indexOf(this.toc[index].href) >= 0) {
            if (!this.toc[index].canTry) {
              this.BuyDialog = true;
              this.needBuy = true;
            }

            return this.toc[index].canTry;
          }
        }

        //兼容分部分的情况

        let chapNum = this.getChapterNum(url);
        if (chapNum > this.limitSection) {
          this.BuyDialog = true;
          this.needBuy = true;
          return false;
        } else {
          //this.BuyDialog = false;
          //this.needBuy = false;
          return true;
        }
      } else {
        return true;
      }

      // //是否有章节限制
      // if (this.limitSection == null) {
      //   console.log("  return true;");
      //   return true;
      // }
    },

    getPathFromUrl(url) {
      let href = window.location.href;
      let path = url.substring(this.localPathname.length - 1, url.length);
      return path;
    },

    //重写epub的request方法

    myEpubRequest(url, type, withCredentials, headers) {
      // console.log("myEpubRequest====>", url);
      //native.showToast("request" + url);

      //判斷是否超過試閱限制

      if (!this.checkChapterCanRead(url)) {
        var deferred = new defer();
        return deferred.promise;
      }

      //替换加密URL
      // let href = window.location.href;
      // //window.location.href.split("/reader.html")[0];
      // let path = url.substring(
      //   window.location.href.split("/reader.html")[0].length,
      //   url.length
      // );

      let path = this.getPathFromUrl(url);
      // path = this.bookId + path;

      let sUrl = this.signatureUrl(path);
      url = sUrl;

      let that = this;

      var supportsURL = typeof window != "undefined" ? window.URL : false; // TODO: fallback for url if window isn't defined
      var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer";

      var deferred = new defer();

      var xhr = new XMLHttpRequest();

      var xhrPrototype = XMLHttpRequest.prototype;

      var header;

      if (!("overrideMimeType" in xhrPrototype)) {
        // IE10 might have response, but not overrideMimeType
        Object.defineProperty(xhrPrototype, "overrideMimeType", {
          value: function xmlHttpRequestOverrideMimeType() {}
        });
      }

      if (withCredentials) {
        xhr.withCredentials = true;
      }

      function err(e) {
        alert("网络错误" + JSON.stringify(e));
        deferred.reject(e);
      }

      function handler() {
        if (this.readyState === XMLHttpRequest.DONE) {
          var responseXML = false;

          if (this.responseType === "" || this.responseType === "document") {
            responseXML = this.responseXML;
          }

          if (this.status === 200 || this.status === 0 || responseXML) {
            //-- Firefox is reporting 0 for blob urls
            var r;

            if (!this.response && !responseXML) {
              alert("Empty Response");
              deferred.reject({
                status: this.status,
                message: "Empty Response",
                stack: new Error().stack
              });
              return deferred.promise;
            }

            if (this.status === 403) {
              alert("request 403");
              deferred.reject({
                status: this.status,
                response: this.response,
                message: "Forbidden",
                stack: new Error().stack
              });
              return deferred.promise;
            }
            if (responseXML) {
              r = this.responseXML;
            } else if (isXml(type)) {
              // xhr.overrideMimeType("text/xml"); // for OPF parsing
              // If this.responseXML wasn't set, try to parse using a DOMParser from text

              r = parse(this.response, "text/xml");
            } else if (type == "xhtml") {
              /**
               *
               */

              //要在这里解密
              // var decryptedRes = that.decryptStr(
              //   this.response,
              //   "ZGIyMTM5NTYxYzlmZTA2OA=="
              // );

              /**
               *
               */

              //替换DIV
              r = parse(this.response, "application/xhtml+xml");
            } else if (type == "html" || type == "htm") {
              r = parse(this.response, "text/html");
            } else if (type == "json") {
              r = JSON.parse(this.response);
            } else if (type == "blob") {
              if (supportsURL) {
                r = this.response;
              } else {
                //-- Safari doesn't support responseType blob, so create a blob from arraybuffer
                r = new Blob([this.response]);
              }
            } else {
              r = this.response;
            }
            deferred.resolve(r);
          } else {
            alert("加载数据发生错误");
            deferred.reject({
              status: this.status,
              message: this.response,
              stack: new Error().stack
            });
          }
        }
      }

      xhr.onreadystatechange = handler;
      xhr.onerror = err;

      xhr.open("GET", url, true);

      for (header in headers) {
        xhr.setRequestHeader(header, headers[header]);
      }

      if (type == "json") {
        xhr.setRequestHeader("Accept", "application/json");
      }

      // If type isn"t set, determine it from the file extension
      if (!type) {
        type = new Path(url).extension;
      }

      if (type == "blob") {
        xhr.responseType = BLOB_RESPONSE;
      }

      if (isXml(type)) {
        // xhr.responseType = "document";
        xhr.overrideMimeType("text/xml"); // for OPF parsing
      }

      if (type == "xhtml") {
        // xhr.responseType = "document";
        //调试
        //xhr.responseType = "arraybuffer";
      }

      if (type == "html" || type == "htm") {
        // xhr.responseType = "document";
      }

      if (type == "binary") {
        xhr.responseType = "arraybuffer";
      }

      xhr.send();

      return deferred.promise;
    },

    //对服务端返回密文进行解密
    decryptStr(encryptStr, keyStr) {
      //要再这里解密
      var key = CryptoJS.enc.Base64.parse(keyStr);
      var iv = CryptoJS.enc.Base64.parse(keyStr);
      // 拿到字符串类型的密文需要先将其用Hex方法parse一下
      var cipherTextHexStr = CryptoJS.enc.Hex.parse(encryptStr);
      var decrypted = CryptoJS.AES.decrypt(
        { ciphertext: cipherTextHexStr },
        key,
        {
          iv: iv,
          padding: CryptoJS.pad.Pkcs7,
          mode: CryptoJS.mode.CBC
        }
      );
      return decrypted.toString(CryptoJS.enc.Utf8);
    },

    loadBook(url) {
      //native.showToast("loadBook！" + url); // 调试的
      this.book = ePub(url, { requestMethod: this.myEpubRequest });
      this.rendition = this.book.renderTo("area", {
        manager: "continuous",
        width: parseInt(this.windowWidth) + "px",
        height: parseInt(this.windowHeight) + "px",
        flow: "paginated",
        snap: true
        // spreads: false,
        // forceEvenPages: true
      });

      //獲取目錄
      this.book.loaded.navigation.then(navigation => {
        //构建目录
        this.toc = navigation.toc;

        //设置试读限制
        let finded = false;
        this.toc.forEach(item => {
          let chapterNum = this.getChapterNum(item.href);
          if (chapterNum > 0 && chapterNum == this.limitSection) {
            finded = true;
            if (chapterNum <= this.limitSection) {
              item.canTry = true;
            } else {
              item.canTry = false;
            }
          } else {
            if (!finded) {
              item.canTry = true;
            } else {
              item.canTry = false;
            }
          }
        });
      });
      //设置hook
      this.setHook();

      this.rendition.on("relocated", locationCfi => {
        // console.log("relocated", JSON.stringify(locationCfi));

        //构造进度
        let index = locationCfi.start.index;
        let chapterNum = this.getChapterNum(locationCfi.start.href);

        // if (this.limitSection && index + 1 > this.limitSection) {
        //   //超過試讀顯示
        //   this.needBuy = true;
        //   this.BuyDialog = true;
        //   return;
        // }

        let contents = this.rendition.getContents();

        let page = locationCfi.start.displayed.page;
        //校正页数
        if (this.checkPage && this.historyPage != page) {
          if (this.tryTime < 5) {
            this.tryTime++;
            if (this.historyPage > page) {
              //往后移动一页
              this.rendition.next();
            } else {
              //往前移动一页
              this.rendition.prev();
            }
            return;
          } else {
            this.checkPage = false;
            setTimeout(() => {
              this.showLoadingMask = false;
            }, 500);
          }
        }
        if (this.historyPage == page) {
          setTimeout(() => {
            this.showLoadingMask = false;
          }, 500);
          this.checkPage = false;
        }

        let total = locationCfi.start.displayed.total;
        this.progress = (page / total) * 100;
        let startCfi = locationCfi.start.cfi;
        let endCfi = locationCfi.end.cfi;
        let srartCfiStr = startCfi.substring(8, startCfi.length - 1);
        let endCfiStr = endCfi.substring(8, endCfi.length - 1);

        let newCfi = `epubcfi(${srartCfiStr},${endCfiStr})`;

        let cfi = locationCfi.end.cfi; // 改为了end
        let progressStr = `第${chapterNum}章第${page}頁`;
        this.reportProgress(startCfi, progressStr, page);
      });

      this.registThemes(); // 注册设置皮肤
      this.setupStyle(); //设置样式

      this.rendition.on("displayed", () => {
        if (this.isNative) {
          //native.showToast("displayed"); // 调试的
          //alert(JSON.stringify(this.rendition.getContents()));
          native.hideLoading();
          setTimeout(() => {
            this.showLoadingMask = false;
          }, 500);
        }
      });

      this.rendition.on("displayError", err => {
        alert("资源解析错误", JSON.stringify(err));
      });

      if (this.historyCfi) {
        //如果有播放進度，則從上次閱讀開始
        console.log("显示历史进度", this.historyCfi);
        this.checkPage = true;
        this.showLoadingMask = true;
        this.rendition.display(this.historyCfi);
      } else {
        console.log("重头开始阅读");
        this.rendition.display();
      }
    },

    //上報進度
    reportProgress(cfi, progressStr, page) {
      let postD = {
        operate: "play",
        objType: "media",
        objId: this.bookId,
        extraData: JSON.stringify({
          cfi: cfi,
          progress: progressStr,
          page: page
        })
      };
      let url = this.CONFIG.OPERATE.ADD;
      this.GLOBAL_.ccRequest
        .doSessionAxios(url, postD, "POST", "no login")
        .then(res => {})
        .catch(err => {
          console.log("上报阅读进度失败");
        });
    },

    setHook() {
      this.rendition.hooks.content.register(contents => {
        var loaded = Promise.all([
          contents.addStylesheet(this.localPathname + "static2/reader.css")
        ]);
        return loaded;
      });

      this.rendition.hooks.content.register(contents => {
        //替换图片URL
        let imgs = contents.content.querySelectorAll("img");
        imgs.forEach(img => {
          let imgSrc = img.src;

          let path = this.getPathFromUrl(imgSrc);
          let newSrc = this.getImageUrl(path);
          // newSrc += "&x-oss-process=image/resize,w_100";
          img.src = newSrc;
          //添加點擊事件
          img.addEventListener("click", e => {
            this.doClick(e);
          });
        });

        //添加点击事件
        contents.document.addEventListener("click", e => {
          this.doClick(e);
        });

        //给所有的P加上事件
        let ps = contents.content.querySelectorAll("p");
        ps.forEach(p => {
          p.addEventListener("click", e => {
            this.doClick(e);
          });
        });

        /**
         *
         *
         */

        /**
         *
         *
         */

        return contents;
      });
    },

    setupStyle() {
      //读取本地缓存，是否有已选的样式参数
      this.getSetting();
      this.rendition.themes.select(this.$config.themes[this.themeName].name);
      //设置字体,默认14
      this.rendition.themes.fontSize(
        this.$config.fontsizes[this.fontSize].size + "px"
      );
      //this.backgroundColor = this.$config.themes[this.themeName].color;
    },

    //注册皮肤
    registThemes() {
      //黑色皮肤
      this.rendition.themes.register("dark", {
        body: {
          color: "#b5b5b5 !important",
          background: "#232733 "
        },
        p: {
          color: "#b5b5b5 !important"
        },
        h1: {
          color: "#b5b5b5 !important"
        },
        h2: {
          color: "#b5b5b5 !important"
        },
        h3: {
          color: "#b5b5b5 !important"
        },
        h4: {
          color: "#b5b5b5 !important"
        },
        a: {
          color: "#b5b5b5",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
      //白色
      this.rendition.themes.register("light", {
        body: { color: "#000 !important", background: "#fff" },
        p: { color: "#000 !important" },
        h1: {
          color: "#000 !important"
        },
        h2: {
          color: "#000 !important"
        },
        h3: {
          color: "#000 !important"
        },
        h4: {
          color: "#000 !important"
        },
        a: {
          color: "#000",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
      //黄色
      this.rendition.themes.register("yellow", {
        body: {
          color: "#000 !important",
          background: "#f6f3e0"
        },
        p: { color: "#000 !important" },
        h1: {
          color: "#000 !important"
        },
        h2: {
          color: "#000 !important"
        },
        h3: {
          color: "#000 !important"
        },
        h4: {
          color: "#000 !important"
        },
        a: {
          color: "#000",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
      //绿色
      this.rendition.themes.register("green", {
        body: { color: "#000 !important", background: "#cdf0d0" },
        p: { color: "#000 !important" },
        h1: {
          color: "#000 !important"
        },
        h2: {
          color: "#000 !important"
        },
        h3: {
          color: "#000 !important"
        },
        h4: {
          color: "#000 !important"
        },
        a: {
          color: "#000",
          "text-decoration": " none"
        },
        img: {
          "max-width": "100%"
        }
      });
    },

    //打开目录
    openCatalog() {
      this.$refs.toolBar.doHide();
      this.showCatagory = new Date().getTime();
    },

    //切换上一页
    prev() {
      if (this.rendition) {
        this.rendition.prev();
      }
    },
    //切换下一页
    next() {
      console.log("需要购买", this.needBuy);

      if (!this.needBuy && this.rendition) {
        //防止点取消购买，还可以切换下一页
        this.rendition.next();
      }
    },
    //屏幕点击事件
    doClick(e) {
      //点击的X坐标
      // let clickX = e.clientX;
      // if (clickX < this.clientWidth / 3) {
      //   //点击屏幕左边1/3
      //   //this.prev();
      // } else if (clickX > (this.clientWidth * 2) / 3) {
      //   //点击右边1/3
      //   //this.next();
      // } else {
      //   this.showToolBar = new Date().getTime();
      // }

      this.showToolBar = new Date().getTime();
    },

    onChangeFontsize(fontsize) {
      this.fontSize = fontsize;
      this.rendition.themes.fontSize(
        this.$config.fontsizes[this.fontSize].size + "px"
      );
      this.saveSettingToLocal();
    },
    onThemeSelect(theme) {
      let themeConfig = this.$config.themes[theme];
      this.themeName = theme;
      this.rendition.themes.select(themeConfig.name);
      this.saveSettingToLocal();
    },

    saveSettingToLocal() {
      let settingObj = {
        fontSize: this.fontSize,
        themeName: this.themeName
      };
      //保存設置到本地
      if (this.isNative) {
        var setData = {
          key: "reader_setting",
          value: JSON.stringify(settingObj)
        };
        native.setStorage(JSON.stringify(setData));
      }
    },

    //從本地緩存中讀取
    getSetting() {
      try {
        var dataValue = native.getStorage("reader_setting");
        let settingObj = JSON.parse(dataValue);
        this.fontSize = settingObj.fontSize;
        this.themeName = settingObj.themeName;
      } catch (error) {}
    },

    //目录跳转
    gotoPage(href) {
      //判斷目標路徑是否超出閱讀限制
      //判斷是否超過試閱限制
      console.log("跳转章节=》", href);
      if (!this.checkChapterCanRead(href)) {
        return;
      }
      this.rendition.display(href);
    }
  }
};
//
</script>

<style lang="less" scoped>
@import "~vux/src/styles/close.less";

.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.guideMask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 999;
  background: rgba(0, 0, 0, 0.6);
}

.loading_mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 999;
  background: rgba(255, 255, 255, 1);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

.guideMaskImg {
  width: 100vw;
  height: 100vh;
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 99;
}

#area {
  padding-top: 3vh;
}

#prev {
  left: 40px;
}

#next {
  right: 40px;
}

.contents-1 {
}
</style>
